#!/usr/bin/env tclsh
# $Id: test6.tcl 9ce65bed8ef4 2012/08/26 02:14:51 pgurumur $
# Copyright (c) 2012 Prabhu Gurumurthy <pgurumur@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

# __version__  = "$Revision: 9ce65bed8ef4 $"
# __author__   = "$Author: pgurumur $"
# __modified__ = "$Date: 2012-08-26 02:14:51Z $"

proc normalize address {
   set temp [list]
   set maxval 8
   set octet [split $address :]
   set octval [expr $maxval - [expr [llength $octet] - 1]]

   set tvalue [llength $octet]
   set toct [lindex $octet end]

   set index 1
   foreach value $octet {
      if {[string length $value]} {
         lappend temp $value
      } else {
         for {set ix $index} {$ix <= $octval} {incr ix} {
            if {[llength $temp] < 8} {
               lappend temp "0000"
            }
         }

         if {$tvalue == 3 && $toct > 0} {
            set index $octval
         }
      }
   }

   puts $temp
   puts [llength $temp]
}

set addrlist "::1 :: 2001:1868:209::/48 2001:0500:0000:ffcf::/64 \
   fe80::215:c5ff:fe78:5fb6/64 2001::ffde:abcd:edab:cdef:abcd/64 \
   2001:1868:209:abdc:abdc::defc/64"

foreach ip $addrlist {
   set var [split $ip /]
   if {[llength $var] == 2} {
      set addr [lindex $var 0]
   } else {
      set addr $ip
   }

   normalize $addr
}
